package com.example.ccmusic

import android.content.ContentResolver
import android.database.Cursor
import android.provider.MediaStore.Audio.Media
import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch

private const val TAG = "MusicViewModel"

class MusicViewModel : ViewModel() {
    private val currentMusic: MutableLiveData<Music> = MutableLiveData()
    private val allMusic: MutableLiveData<List<Music>> = MutableLiveData()

    fun currentMusic() = currentMusic

    fun allMusic() = allMusic

    fun changeCurrentMusic(music: Music) {
        currentMusic.value = music
    }

    fun findAllMusic() {
        viewModelScope.launch {

        }
    }

    fun queryMusic(contentResolver: ContentResolver): ArrayList<Music> {
        Log.d(TAG, "queryMusic")
        val list = ArrayList<Music>()
        val resolver: ContentResolver = contentResolver
        val uri = Media.EXTERNAL_CONTENT_URI
        val cursor: Cursor? = resolver.query(uri, null, null, null, null)
        when {
            cursor == null -> {
                // query failed, handle error.
            }
            !cursor.moveToFirst() -> {
                // no media on the device
            }
            else -> {
                // Absolute filesystem path to the media item on disk.
                val dataColumn = cursor.getColumnIndex(Media.DATA)
                val authorColumn = cursor.getColumnIndex(Media.AUTHOR)
                val titleColumn = cursor.getColumnIndex(Media.TITLE)
                val albumIdColumn = cursor.getColumnIndex(Media.ALBUM_ID)
                val nameColumn = cursor.getColumnIndex(Media.DISPLAY_NAME)
                val artistColumn = cursor.getColumnIndex(Media.ARTIST)
                val durationColumn = cursor.getColumnIndex(Media.DURATION)
                do {
                    val path = cursor.getString(dataColumn)
                    val author = cursor.getString(authorColumn)
                    val title = cursor.getString(titleColumn)
                    val albumId = cursor.getLong(albumIdColumn)
                    val name = cursor.getString(nameColumn)
                    val artist = cursor.getString(artistColumn)
                    val duration = cursor.getLong(durationColumn)
                    if (duration < 1000 * 30) continue
                    if (artist == "<unknown>") continue
//                    Log.d(TAG, "queryMusic: path = $path, author = $author, title = $title, albumID = $albumId, name = $name, artist = $artist, duration = $duration")
                    val music = Music(title, artist, path, albumId, duration)
                    list.add(music)

                } while (cursor.moveToNext())
            }
        }
        cursor?.close()
        return list
    }
}